#include "bormane.h"
#include "ui_bormane.h"
#include<QDebug>
#include<QMessageBox>
#include <QDialog>
#include <QFormLayout>
#include <QLineEdit>
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QSqlQuery>
borMane::borMane(QSqlDatabase &d) :
//    QWidget(parent),
    db(d),

    ui(new Ui::borMane)
{
    ui->setupUi(this);
    nowmode=SName;
    d_model=new QSqlTableModel(this,db);
    d_model->setTable("borrow");
    d_model->setEditStrategy(QSqlTableModel::OnManualSubmit);//设置手动提交修改
//    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);//设置不能编辑表格
    ui->tableView->setEditTriggers(QTableView::DoubleClicked);//设置双击后可以编辑
    getAll();
}

borMane::~borMane()
{
    delete ui;
}


void borMane::on_rueBut_clicked()
{
    d_model->submitAll();
    getAll();
}

void borMane::on_addBut_clicked()
{
    getAll(); // 刷新用户列表
    ui->tableView->scrollToBottom();
}

void borMane::on_delBut_clicked()
{
    // 获取选中的行
    QModelIndexList selectedIndexes = ui->tableView->selectionModel()->selectedIndexes();
    if (selectedIndexes.isEmpty()) {
        QMessageBox::warning(this, tr("请现在"), tr("请选择要归还的记录。"));
        return;
    }

    // 获取选中行的主键值
    QModelIndex index = selectedIndexes.first();
    int id = d_model->data(d_model->index(index.row(), 0)).toInt();
    int b_id = d_model->data(d_model->index(index.row(), 3)).toInt();
    int count = d_model->data(d_model->index(index.row(), 4)).toInt();
    qDebug() << count;
    // 确认删除
    if (QMessageBox::question(this, tr("确认"), tr("确定归还书籍？"),
                              QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
        return;
    }

    // 执行操作

    QSqlQuery query(d_model->database());
    qDebug()<<id;

        QString sql = QString("update borrow set J_Hs = CURRENT_time where J_Id = %1;").arg(id);
        query.exec(sql);

        sql = QString("update book set B_Cou = B_Cou + (%1) where B_Id = %2;").arg(count).arg(b_id);

        if (query.exec(sql)) {
            QMessageBox::information(this, tr("成功"), tr("归还成功。"));
        } else {
            QMessageBox::critical(this, tr("错误"), tr("归还失败：") + query.lastError().text());
        }
           // 调用存储过程
        QString callProc = QString("CALL `删除已还书记录`(%1)").arg(count);
           QSqlQuery callQuery(db);
           if (!callQuery.exec(callProc)) {
               qDebug() << "调用存储过程失败:" << callQuery.lastError();
           }

    d_model->submitAll();
    getAll();
}

void borMane::on_findBut_clicked()
{
    QString search = ui->searchEdit->text();

    // 根据条件查询
    QSqlQueryModel *queryModel = new QSqlQueryModel(this);
    if(nowmode==SId)
        queryModel->setQuery(QString("select * from borrow where J_Xh = (SELECT S_Id FROM student WHERE S_Id = '%1')")
                         .arg(search), db);
    else if(nowmode==SName)
        queryModel->setQuery(QString("select * from borrow where J_Xh = (SELECT S_Id FROM student WHERE S_Name LIKE '%%1%')")
                         .arg(search), db);
    if(nowmode==BName)
        queryModel->setQuery(QString("select * from borrow where J_Book = (SELECT B_Id FROM book WHERE B_Name LIKE '%%1%')")
                         .arg(search), db);
    if(nowmode==BId)
        queryModel->setQuery(QString("select * from borrow where J_Book = (SELECT B_Id FROM book WHERE B_Id = '%1')")
                         .arg(search), db);
    if (queryModel->lastError().type() != QSqlError::NoError) {
        qDebug() << "查询错误:" << queryModel->lastError();
        QMessageBox::critical(this, tr("错误"), tr("查询失败：") + queryModel->lastError().text());
        return;
    }

    // 显示查询结果
    ui->tableView->setModel(queryModel);
    QStringList chineseHeaders;
    chineseHeaders << tr("借阅编号") << tr("联系方式") << tr("学号")<< tr("图书编号")<< tr("数量")<< tr("借阅日期")<< tr("归还日期")<< tr("应还日期");
    for (int i = 0; i < chineseHeaders.size(); ++i) {
        queryModel->setHeaderData(i, Qt::Horizontal, chineseHeaders[i]);
    }

    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}


void borMane::getAll()
{
    if(!d_model->select()){
        qDebug()<<"连接错误";
    }
    ui->tableView->setModel(d_model);
    // 设置中文表头
        QStringList chineseHeaders;
        chineseHeaders << tr("借阅编号") << tr("联系方式") << tr("学号")<< tr("图书编号")<< tr("数量")<< tr("借阅日期")<< tr("归还日期");
        for (int i = 0; i < chineseHeaders.size(); ++i) {
            d_model->setHeaderData(i, Qt::Horizontal, chineseHeaders[i]);
        }

        ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}



void borMane::on_comboBox_currentTextChanged(const QString &arg1)
{
    if(arg1=="借阅人姓名"){
        nowmode=SName;
    }else if(arg1=="借阅书籍"){
        nowmode=BName;
    }else if (arg1=="图书编号") {
        nowmode=BId;
}else if (arg1=="借阅人账号") {
    nowmode=SId;
}
}
